package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.UserDTO;
import com.yuelao.yuelao_backend.dto.request.UpdateUserRequest;
import com.yuelao.yuelao_backend.entity.*;
import com.yuelao.yuelao_backend.mapper.*;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户Service实现类
 * 重构说明：适配User + UserProfile + UserAlbum + UserSettings的新表结构
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserProfileMapper userProfileMapper;
    
    @Resource
    private UserAlbumMapper userAlbumMapper;
    
    @Resource
    private UserSettingsMapper userSettingsMapper;
    
    @Resource
    private UserCoinAccountMapper userCoinAccountMapper;
    
    @Resource
    private AchievementService achievementService;

    @Override
    public UserDTO getUserInfo(Long userId) {
        log.debug("开始查询用户信息: userId={}", userId);
        
        // 1. 查询用户基础信息
        User user = getById(userId);
        if (user == null) {
            log.warn("用户不存在: userId={}", userId);
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        
        // 2. 查询用户详细资料
        LambdaQueryWrapper<UserProfile> profileWrapper = new LambdaQueryWrapper<>();
        profileWrapper.eq(UserProfile::getUserId, userId);
        UserProfile profile = userProfileMapper.selectOne(profileWrapper);
        
        // 3. 查询用户相册
        LambdaQueryWrapper<UserAlbum> albumWrapper = new LambdaQueryWrapper<>();
        albumWrapper.eq(UserAlbum::getUserId, userId)
                   .eq(UserAlbum::getStatus, 1)
                   .orderByAsc(UserAlbum::getSortOrder);
        List<UserAlbum> albums = userAlbumMapper.selectList(albumWrapper);
        
        // 4. 转换为DTO，并脱敏敏感信息（手机号、微信号、QQ号）
        UserDTO dto = convertToUserDTO(user, profile, albums);
        dto.setPhone(maskPhone(dto.getPhone()));
        dto.setWechat(maskContact(dto.getWechat()));
        dto.setQq(maskContact(dto.getQq()));
        
        // 5. 检查登录相关成就
        achievementService.checkLoginAchievements(userId);
        
        log.debug("用户信息查询成功: userId={}, nickname={}", userId, user.getNickname());
        return dto;
    }

    @Override
    public UserDTO getCurrentUser(Long currentUserId) {
        // 1. 查询用户基础信息
        User user = getById(currentUserId);
        if (user == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        
        // 2. 查询用户详细资料
        LambdaQueryWrapper<UserProfile> profileWrapper = new LambdaQueryWrapper<>();
        profileWrapper.eq(UserProfile::getUserId, currentUserId);
        UserProfile profile = userProfileMapper.selectOne(profileWrapper);
        
        // 3. 查询用户相册
        LambdaQueryWrapper<UserAlbum> albumWrapper = new LambdaQueryWrapper<>();
        albumWrapper.eq(UserAlbum::getUserId, currentUserId)
                   .eq(UserAlbum::getStatus, 1)
                   .orderByAsc(UserAlbum::getSortOrder);
        List<UserAlbum> albums = userAlbumMapper.selectList(albumWrapper);
        
        // 4. 转换为DTO，返回完整信息（包括手机号、微信号、QQ号）
        return convertToUserDTO(user, profile, albums);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserInfo(Long currentUserId, UpdateUserRequest request) {
        log.info("开始更新用户信息: userId={}", currentUserId);
        
        // 1. 查询用户基础信息
        User user = getById(currentUserId);
        if (user == null) {
            log.warn("用户不存在: userId={}", currentUserId);
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 2. 更新基本信息（users表）
        if (StringUtils.hasText(request.getNickname())) {
            user.setNickname(request.getNickname());
        }
        if (StringUtils.hasText(request.getGender())) {
            user.setGender(request.getGender());
        }
        if (request.getBirthdate() != null) {
            user.setBirthday(request.getBirthdate());
            user.setAge(Period.between(request.getBirthdate(), LocalDate.now()).getYears());
        }
        if (StringUtils.hasText(request.getAvatar())) {
            user.setAvatar(request.getAvatar());
        }
        if (StringUtils.hasText(request.getWechat())) {
            user.setWechat(request.getWechat());
        }
        if (StringUtils.hasText(request.getQq())) {
            user.setQq(request.getQq());
        }
        user.setUpdatedAt(LocalDateTime.now());
        updateById(user);


        // 3. 更新用户详细资料（user_profiles表）
        LambdaQueryWrapper<UserProfile> profileWrapper = new LambdaQueryWrapper<>();
        profileWrapper.eq(UserProfile::getUserId, currentUserId);
        UserProfile profile = userProfileMapper.selectOne(profileWrapper);
        
        if (profile == null) {
            // 如果不存在，创建新的profile
            profile = new UserProfile();
            profile.setUserId(currentUserId);
        }
        
        if (StringUtils.hasText(request.getHometownProvince())) {
            profile.setHometownProvince(request.getHometownProvince());
        }
        if (StringUtils.hasText(request.getHometownCity())) {
            profile.setHometownCity(request.getHometownCity());
        }
        if (StringUtils.hasText(request.getResidenceProvince())) {
            profile.setResidenceProvince(request.getResidenceProvince());
        }
        if (StringUtils.hasText(request.getResidenceCity())) {
            profile.setResidenceCity(request.getResidenceCity());
        }
        if (request.getHeight() != null) {
            profile.setHeight(request.getHeight());
        }
        if (StringUtils.hasText(request.getEducation())) {
            profile.setEducation(request.getEducation());
        }
        if (StringUtils.hasText(request.getSchool())) {
            profile.setSchool(request.getSchool());
        }
        if (StringUtils.hasText(request.getOccupation())) {
            profile.setOccupation(request.getOccupation());
        }
        if (StringUtils.hasText(request.getIncome())) {
            profile.setIncome(request.getIncome());
        }
        if (StringUtils.hasText(request.getHouse())) {
            profile.setHouse(request.getHouse());
        }
        if (StringUtils.hasText(request.getCar())) {
            profile.setCar(request.getCar());
        }
        if (StringUtils.hasText(request.getMaritalStatus())) {
            profile.setMaritalStatus(request.getMaritalStatus());
        }
        if (StringUtils.hasText(request.getIntroduction())) {
            profile.setIntroduction(request.getIntroduction());
        }
        if (StringUtils.hasText(request.getRequirements())) {
            profile.setRequirements(request.getRequirements());
        }
        if (!CollectionUtils.isEmpty(request.getHobbies())) {
            profile.setHobbies(request.getHobbies());
        }
        if (!CollectionUtils.isEmpty(request.getPurposes())) {
            profile.setPurposes(request.getPurposes());
        }

        profile.setUpdatedAt(LocalDateTime.now());
        if (profile.getId() == null) {
            userProfileMapper.insert(profile);
        } else {
            userProfileMapper.updateById(profile);
        }

        // 4. 更新相册（user_albums表）
        List<UserAlbum> updatedAlbums = new ArrayList<>();
        if (!CollectionUtils.isEmpty(request.getAlbumUrls())) {
            // 先删除旧相册
            LambdaQueryWrapper<UserAlbum> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(UserAlbum::getUserId, currentUserId);
            userAlbumMapper.delete(deleteWrapper);
            
            // 插入新相册
            for (int i = 0; i < request.getAlbumUrls().size(); i++) {
                UserAlbum album = new UserAlbum();
                album.setUserId(currentUserId);
                album.setImageUrl(request.getAlbumUrls().get(i));
                album.setSortOrder(i);
                album.setIsCover(i == 0); // 第一张设为封面
                album.setStatus(1);
                album.setCreatedAt(LocalDateTime.now());
                userAlbumMapper.insert(album);
                updatedAlbums.add(album);
            }
        } else {
            // 如果没有更新相册，查询现有相册
            LambdaQueryWrapper<UserAlbum> albumWrapper = new LambdaQueryWrapper<>();
            albumWrapper.eq(UserAlbum::getUserId, currentUserId)
                       .eq(UserAlbum::getStatus, 1)
                       .orderByAsc(UserAlbum::getSortOrder);
            updatedAlbums = userAlbumMapper.selectList(albumWrapper);
        }

        // 5. 计算资料完整度并检查相关成就
        int completionPercentage = calculateProfileCompletion(user, profile, updatedAlbums);
        achievementService.checkProfileCompletionAchievements(currentUserId, completionPercentage);

        log.info("用户信息更新成功: userId={}, nickname={}", currentUserId, user.getNickname());
        return true;
    }

    @Override
    public List<UserDTO> getRecommendUsers(int pageNum, int pageSize) {
        log.debug("开始查询推荐用户列表: pageNum={}, pageSize={}", pageNum, pageSize);
        
        Page<User> page = new Page<>(pageNum, pageSize);
        // 示例：按年龄和性别推荐，实际应根据推荐算法
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getStatus, 1) // 1-正常
                .orderByDesc(User::getIsVip)
                .orderByDesc(User::getUpdatedAt); // 简单排序，实际应是复杂的推荐逻辑

        Page<User> userPage = page(page, queryWrapper);
        log.debug("查询到推荐用户: count={}", userPage.getRecords().size());
        
        // 批量查询用户的Profile和Album
        return userPage.getRecords().stream()
                .map(user -> {
                    // 查询用户详细资料
                    LambdaQueryWrapper<UserProfile> profileWrapper = new LambdaQueryWrapper<>();
                    profileWrapper.eq(UserProfile::getUserId, user.getId());
                    UserProfile profile = userProfileMapper.selectOne(profileWrapper);
                    
                    // 查询用户相册
                    LambdaQueryWrapper<UserAlbum> albumWrapper = new LambdaQueryWrapper<>();
                    albumWrapper.eq(UserAlbum::getUserId, user.getId())
                               .eq(UserAlbum::getStatus, 1)
                               .orderByAsc(UserAlbum::getSortOrder);
                    List<UserAlbum> albums = userAlbumMapper.selectList(albumWrapper);
                    
                    // 转换为DTO并脱敏敏感信息
                    UserDTO dto = convertToUserDTO(user, profile, albums);
                    dto.setPhone(maskPhone(dto.getPhone()));
                    dto.setWechat(maskContact(dto.getWechat()));
                    dto.setQq(maskContact(dto.getQq()));
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public UserDTO convertToUserDTO(User user) {
        if (user == null) {
            return null;
        }
        
        // 查询关联数据
        LambdaQueryWrapper<UserProfile> profileWrapper = new LambdaQueryWrapper<>();
        profileWrapper.eq(UserProfile::getUserId, user.getId());
        UserProfile profile = userProfileMapper.selectOne(profileWrapper);
        
        LambdaQueryWrapper<UserAlbum> albumWrapper = new LambdaQueryWrapper<>();
        albumWrapper.eq(UserAlbum::getUserId, user.getId())
                   .eq(UserAlbum::getStatus, 1)
                   .orderByAsc(UserAlbum::getSortOrder);
        List<UserAlbum> albums = userAlbumMapper.selectList(albumWrapper);
        
        // 转换为DTO并脱敏敏感信息
        UserDTO dto = convertToUserDTO(user, profile, albums);
        dto.setPhone(maskPhone(dto.getPhone()));
        dto.setWechat(maskContact(dto.getWechat()));
        dto.setQq(maskContact(dto.getQq()));
        
        return dto;
    }
    
    /**
     * 手机号脱敏处理
     * 保留前3位和后4位，中间用***替换
     * 例如：13812345678 -> 138****5678
     * @param phone 原始手机号
     * @return 脱敏后的手机号
     */
    private String maskPhone(String phone) {
        if (phone == null || phone.length() < 7) {
            return phone;
        }
        if (phone.length() == 11) {
            // 标准11位手机号：保留前3位和后4位
            return phone.substring(0, 3) + "****" + phone.substring(7);
        } else {
            // 其他长度：保留前3位和后2位
            return phone.substring(0, 3) + "***" + phone.substring(phone.length() - 2);
        }
    }
    
    /**
     * 联系方式脱敏处理（微信号、QQ号等）
     * 长度大于6：保留前2位和后2位，中间用***替换
     * 长度4-6：保留首尾各1位，中间用***替换
     * 例如：wechat123 -> we***23
     * @param contact 原始联系方式
     * @return 脱敏后的联系方式
     */
    private String maskContact(String contact) {
        if (contact == null || contact.length() <= 3) {
            return contact;
        }
        if (contact.length() > 6) {
            // 长度大于6：保留前2位和后2位
            return contact.substring(0, 2) + "***" + contact.substring(contact.length() - 2);
        } else {
            // 长度4-6：保留首尾各1位
            return contact.substring(0, 1) + "***" + contact.substring(contact.length() - 1);
        }
    }
    
    /**
     * 转换User实体为UserDTO
     * @param user 用户基础信息
     * @param profile 用户详细资料
     * @param albums 用户相册
     * @return UserDTO
     */
    private UserDTO convertToUserDTO(User user, UserProfile profile, List<UserAlbum> albums) {
        if (user == null) {
            return null;
        }
        
        UserDTO dto = new UserDTO();
        
        // 基础信息（来自users表）
        dto.setId(user.getId());
        dto.setPhone(user.getPhone());
        dto.setNickname(user.getNickname());
        dto.setGender(user.getGender());
        dto.setBirthdate(user.getBirthday());
        dto.setAge(user.getAge());
        dto.setAvatar(user.getAvatar());
        dto.setIsVip(user.getIsVip());
        dto.setWechat(user.getWechat());
        dto.setQq(user.getQq());
        
        // 详细资料（来自user_profiles表）
        if (profile != null) {
            dto.setHometownProvince(profile.getHometownProvince());
            dto.setHometownCity(profile.getHometownCity());
            dto.setResidenceProvince(profile.getResidenceProvince());
            dto.setResidenceCity(profile.getResidenceCity());
            dto.setHeight(profile.getHeight());
            dto.setEducation(profile.getEducation());
            dto.setSchool(profile.getSchool());
            dto.setOccupation(profile.getOccupation());
            dto.setIncome(profile.getIncome());
            dto.setHouse(profile.getHouse());
            dto.setCar(profile.getCar());
            dto.setMaritalStatus(profile.getMaritalStatus());
            dto.setIntroduction(profile.getIntroduction());
            dto.setRequirements(profile.getRequirements());
            dto.setHobbies(profile.getHobbies());
            dto.setPurposes(profile.getPurposes());
        }
        
        // 相册（来自user_albums表）
        if (!CollectionUtils.isEmpty(albums)) {
            List<String> albumUrls = albums.stream()
                    .map(UserAlbum::getImageUrl)
                    .collect(Collectors.toList());
            dto.setAlbumUrls(albumUrls);
        } else {
            dto.setAlbumUrls(new ArrayList<>());
        }
        
        return dto;
    }
    
    /**
     * 计算用户资料完整度
     * @param user 用户基础信息
     * @param profile 用户详细资料
     * @param albums 用户相册
     * @return 完整度百分比（0-100）
     */
    private int calculateProfileCompletion(User user, UserProfile profile, List<UserAlbum> albums) {
        int totalFields = 0;
        int filledFields = 0;
        
        // 基础信息字段（权重较高）
        if (StringUtils.hasText(user.getNickname())) {
            filledFields++;
        }
        totalFields++;
        
        if (user.getGender() != null) {
            filledFields++;
        }
        totalFields++;
        
        if (user.getBirthday() != null) {
            filledFields++;
        }
        totalFields++;
        
        if (StringUtils.hasText(user.getAvatar())) {
            filledFields++;
        }
        totalFields++;
        
        // 相册（权重高）
        if (!CollectionUtils.isEmpty(albums)) {
            filledFields++;
        }
        totalFields++;
        
        // 详细资料字段
        if (profile != null) {
            if (StringUtils.hasText(profile.getHometownProvince())) {
                filledFields++;
            }
            totalFields++;
            
            if (StringUtils.hasText(profile.getResidenceProvince())) {
                filledFields++;
            }
            totalFields++;
            
            if (profile.getHeight() != null) {
                filledFields++;
            }
            totalFields++;
            
            if (StringUtils.hasText(profile.getEducation())) {
                filledFields++;
            }
            totalFields++;
            
            if (StringUtils.hasText(profile.getOccupation())) {
                filledFields++;
            }
            totalFields++;
            
            if (StringUtils.hasText(profile.getIncome())) {
                filledFields++;
            }
            totalFields++;
            
            if (StringUtils.hasText(profile.getIntroduction())) {
                filledFields++;
            }
            totalFields++;
            
            if (!CollectionUtils.isEmpty(profile.getHobbies())) {
                filledFields++;
            }
            totalFields++;
        }
        
        // 计算百分比
        if (totalFields == 0) {
            return 0;
        }
        
        return (filledFields * 100) / totalFields;
    }
}